<?php

namespace App\Http\Controllers;

use App\Http\Requests\AuthRequest;
use App\Models\Phone;
use App\Models\Role;
use App\Transformers\UserTransformer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    /**
     * 用户名登录
     */
    protected $username = 'name';

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * @api {post} /api/login 登陆
     * @apiGroup Session
     *
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     * @apiParam {String} name  账号（必传参数）
     * @apiParam {String} password  密码（必传参数）
     *
     * @apiSuccess {String} access_token 登陆凭证
     * @apiSuccess {String} token_type 凭证类型
     * @apiSuccess {String} expires_in 凭证有效期
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *         {
     *              "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9kaWFueXVuLmNvbVwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTU0Mjc2NTc2MywiZXhwIjoxNTQyNzY5MzYzLCJuYmYiOjE1NDI3NjU3NjMsImp0aSI6IjdpbXNWMWJhUklRUmRKQkkiLCJzdWIiOjEsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.xWN6jA542G2UVfvNDpp_e6eIoZDDjaiVP9Vtd7HxIAM",
     *              "token_type": "bearer",
     *              "expires_in": 3600
     *         }
     *
     */
    public function login(AuthRequest $request)
    {
        $credentials = request(['name', 'password']);
        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => '账号或密码不正确'], 401);
        }
        if(Auth::user()->status != 1){
            return response()->json(['error' => '账号被禁用'], 401);
        }
        $data['login_ip'] = $request->getClientIp();
        $data['login_time'] = Carbon::now()->toDateTimeString();
        Auth::user()->update($data);
        return $this->respondWithToken($token);
    }

    /**
     * @api {post} /api/currentUser 登陆用户信息
     * @apiGroup Session
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "id": 1,
     *           "name": "admin",
     *           "email": "genevieve53@example.net",
     *           "email_verified_at": "2018-12-13 10:24:20",
     *           "created_at": null,
     *           "updated_at": "2018-12-13 10:24:20"
     *       }
     */
    public function currentUser(Role $role)
    {
        $res = $role->getIdAndNameToArray();
        $setting = DB::table('phone_settings')->where('status',1)->first();
        if($setting && $setting != 'twilio'){
            $user_id = Auth::id();
            $nameAndPass= Phone::where([
                ['phone_setting_id','=',$setting->id],
                ['user_id','=',$user_id]
            ])->first();
        }
        $nameAndPass = empty($nameAndPass)?'':$nameAndPass;
        return $this->response->item(auth()->user(),new UserTransformer($res,'',$nameAndPass));
    }

    /**
     * @api {post} /api/logout 登出
     * @apiGroup Session
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiSuccess {String} message 消息
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *           {
     *              "message": "退出成功"
     *           }
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => '退出成功']);
    }

    /**
     * @api {post} /api/refresh 刷新
     * @apiGroup Session
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiSuccess {String} access_token 登陆凭证
     * @apiSuccess {String} token_type 凭证类型
     * @apiSuccess {String} expires_in 凭证有效期
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9kaWFueXVuMi5jb21cL2FwaVwvcmVmcmVzaCIsImlhdCI6MTU0NDY2ODQ3NiwiZXhwIjoxNTQ0NjcyMDg3LCJuYmYiOjE1NDQ2Njg0ODcsImp0aSI6InU2V2VmV0tZRU9zZFd3dnYiLCJzdWIiOjEsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.kCjlAlUTM4yFnDDmif7Lzl8ZMht7wNzaeBorUpMtMBI",
     *           "token_type": "Bearer",
     *           "expires_in": 3600
     *       }
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

    /**
     * @api {get} /api/currentPermissions 登陆用户权限(树结构)
     * @apiGroup Permission
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiSuccess {String} message 消息
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                   "id": 1,
     *                   "name": null,
     *                   "alias": "组织架构api",
     *                   "guard_name": "api",
     *                   "_lft": 1,
     *                   "_rgt": 10,
     *                   "parent_id": null,
     *                   "created_at": "2018-12-17 19:29:18",
     *                   "updated_at": "2018-12-18 10:09:07",
     *                   "deleted_at": null,
     *                   "pivot": {
     *                   "role_id": 1,
     *                   "permission_id": 1
     *               },
     *           ]
     8       }
     */
    public function currentPermissions(){
        $permissions = $this->user()->getAllPermissions();
//        $permissions = getTree1($permissions,0,'');
        return response()->json(['data'=>$permissions]);

    }

    /**
     * @api {patch} /api/auth/password/reset 密码修改
     * @apiName AuthPassReset
     * @apiGroup Session
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.urlchecker.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} current_pass  当前密码
     * @apiParam {String} password  新密码
     * @apiParam {String} password_confirmation  确认新密码
     *
     * @apiSuccess {int}   id  用户id
     * @apiSuccess {String}   name  账号名
     * @apiSuccess {String}   email  邮箱
     * @apiSuccess {String}   login_ip  最后登陆IP
     * @apiSuccess {datetime}   login_at  最后登陆时间
     * @apiSuccess {int}   status  状态
     * @apiSuccess {datetime}   created_at  创建时间
     * @apiSuccess {datetime}   updated_at  更新时间
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *           {
     *               "id": 1,
     *               "name": "Anahi Sanford II",
     *               "email": "bkutch@example.org",
     *               "login_ip": "192.168.10.1",
     *               "login_at": "2018-11-21 17:12:20",
     *               "status": 1,
     *               "created_at": "2018-11-21 09:56:20",
     *               "updated_at": "2018-11-21 17:13:56"
     *           }
     */
    public function update(Request $request,Role $role)
    {
        $validatedData = $request->validate([
            'current_pass' => 'required|min:6',
            'password' => 'required|min:6|confirmed|regex:/^[A-Za-z0-9]+$/',
        ],[],[
            'current_pass'=> '当前密码'
        ]);

        $credentials = [
            'name' => $request->user()->name,
            'password' => $validatedData['current_pass']
        ];

        if (Auth::guard('api')->attempt($credentials)) {
            Auth::user()->update(['password' => bcrypt($validatedData['password'])]);
            $res = $role->getIdAndNameToArray();
            return $this->response->item(Auth::user(), new UserTransformer($res));
        } else {
            return response()->json(['message' => '当前密码错误', 'status_code' => 422], 422);
        }
    }
}
